import numpy as np
import pandas as pd
import os

class Person(object):

    def __init__(self, name, addr, telephone_f, telephone_e, mail):
        self.name = name
        self.addr = addr
        self.telephone_f = telephone_f
        self.telephone_e = telephone_e
        self.mail = mail


    def __str__(self):
        return '联系人 {0} 的地址:{1}, 电话号码: {2} ,备用电话号码: {3},邮箱: {4}'.format(self.name, self.addr, self.telephone_f,
                                                                      self.telephone_e, self.mail)

    def browseInfo(self):
        print("\n%s\t%s\t\t%s\t%s\t%s\n" % (self.name, self.addr, self.telephone_f, self.telephone_e, self.mail))


    def getAllInfo(self):
        return [self.name, self.addr, self.telephone_f, self.telephone_e,  self.mail]


    def modifyAttr(self, attr, modifiedValue):
        if attr == 'name':
            self.name = modifiedValue
        elif attr == 'addr':
            self.addr = modifiedValue
        elif attr == 'phone_f':
            self.telephone_f = modifiedValue
        elif attr == 'phone_e':
            self.telephone_e = modifiedValue
        elif attr == 'mail':
            self.mail = modifiedValue
        else:
            pass


class AddressBook(object):
    # 统计通讯录中的人数
    count = 0

    def __init__(self):
        self.container = dict()


    @classmethod
    def changeCount(cls, method):
        if method == '+':
            cls.count += 1
        elif method == '-':
            cls.count -= 1
        else:
            pass

    @classmethod
    def getCount(cls):
        return cls.count


    def isExist(self, name) -> bool:
        """
        判断是否存在通讯录中
        :param name:
        :return: bool
        """
        return name in self.container


    def addPerson(self, name, addr, telephone_f, telephone_e, mail):
        """
        添加一个人的通讯信息
        :param name:
        :param addr:
        :param telephone_f:
        :param telephone_e:
        :param mail:
        :return:
        """
        person = Person(name, addr, telephone_f, telephone_e, mail)
        self.container[name] = person
        self.changeCount('+')


    def delPerson(self, name):
        """
        删除一个人的通讯信息
        :param name:
        :return:
        """

        del self.container[name]
        self.changeCount('-')
        print('联系人已成功删除！')


    def searchPerson(self, name):
        """
        查询某个人的通讯信息
        :param name:
        :return:
        """
        person = self.container[name]
        print(person)


    def browseAddrBook(self):
        """
        浏览通信录所有的人的信息
        :return:
        """
        if len(self.container) > 0:
            print("\n姓名\t地址\t\t电话\t\t备用电话\t\t电子邮箱")
            for person in self.container.values():
                person.browseInfo()
        print("通讯录中一共有%d个人\n" % self.getCount())


    def modifyPerson(self, name, attribute, modifiedValue):
        if name not in self.container.keys():
            print("联系人:%s, 不存在" % name)
            return
        person = self.container['name']
        if attribute == 'name':
            data = person.getAllInfo()
            self.addPerson(modifiedValue, data[1], data[2], data[3], data[4])
            del self.container[name]
        elif attribute == 'addr':
            person.modifyAttr('addr', modifiedValue)
        elif attribute == 'phone1':
            person.modifyAttr('phone_f', modifiedValue)
        elif attribute == 'phone2':
            person.modifyAttr('phone_e', modifiedValue)
        elif attribute == 'mail':
            person.modifyAttr('mail', modifiedValue)
        else:
            pass


    def save_to_file(self):
        """
        保存数据到 excel
        :return:
        """
        datalist = []
        for i in self.container:
            datalist.append(self.container[i].getAllInfo())
        dataFrame = pd.DataFrame(datalist, columns=['姓名', '地址', '电话', '备用电话', '电子邮箱'])
        dataFrame.to_excel('./data.xlsx',sheet_name="通讯录信息汇总表", encoding='utf-8',index=False)
        print("保存成功！")


    def recover_data(self):
        """
        恢复数据
        :return:
        """
        flag = os.path.isfile("./data.xlsx")
        if flag is True:
            dataFrame = pd.read_excel('./data.xlsx', sheet_name=0, encoding='utf-8',skiprows=0)
            for data in dataFrame.values:
                self.addPerson(data[0],data[1],data[2],data[3],data[4])
            print("文本已成功恢复！")
        else:
             print("文本不存在(或未创建)！")


class Input(object):


    @staticmethod
    def add():
        """
        根据用户输入添加联系人信息
        :return:
        """
        name = input('请输入要添加的联系人姓名>>')
        if addrBook.isExist(name):
            print('该联系人已经存在')
            return
        while True:
            addr = input('请输入联系人地址>>')
            break
        while True:
            telephone_f = (input('请输入联系人电话号码(11位)>>'))
            if len(telephone_f) == 11:
                break
            else:
                print("格式错误，请重新输入>>")
        while True:
            telephone_e = (input('请输入联系人备用电话号码(11位)>>'))
            if len(telephone_e) == 11:
                break
            else:
                print("格式错误，请重新输入>>")
        while True:
            mail = (input('请输入联系人邮箱>>'))
            if "@" in mail:
                break
            else:
                print("格式错误，请重新输入>>")
        addrBook.addPerson(name, addr, telephone_f, telephone_e, mail)
        print("联系人已成功录入！")


    @staticmethod
    def search():
        """
        根据输入姓名找出联系人信息
        :return:
        """
        name = (input('请输入要查询的联系人姓名>>'))
        if not addrBook.isExist(name):
            print("联系人:%s, 不存在" % name)
            return
        addrBook.searchPerson(name)


    @staticmethod
    def delete():
        """
        删除指定人的通信录信息
        :return:
        """
        name = (input('请输入要查询的联系人姓名>>'))
        if not addrBook.isExist(name):
            print("联系人:%s, 不存在" % name)
            return
        addrBook.delPerson(name)


    @staticmethod
    def modify():
        """
        指定需要修改的内容
        :return:
        """
        while True:
            name = (input('请输入要修改的联系人姓名(回车退出)>>'))
            if not addrBook.isExist(name):
                print("联系人:%s, 不存在" % name)
                return
            addrBook.searchPerson(name)
            modify_menu()
            while True:
                choice = input("请选择修改类容(序号)>>")
                if choice == "1":
                    newName = input("请输入新的姓名>>")
                    addrBook.modifyPerson(name, 'name', newName)
                    print("------------姓名已经更新------------\n")
                    continue

                elif choice == "2":
                    newAddr = input("请输入新的地址>>")
                    addrBook.modifyPerson(name, 'addr', newAddr)
                    print("------------地址已经更新------------\n")
                    break

                elif choice == "3":
                    while True:
                        newPhone_f = input("请输入新的电话>>")
                        if len(newPhone_f) == 11:
                            addrBook.modifyPerson(name, 'phone_f', newPhone_f)
                            print("------------电话1已经更新------------\n")
                            break
                        else:
                            print("---------输入有误，请重新输入！---------\n")
                            continue

                elif choice == "4":
                    while True:
                        newPhone_e= input("请输入新的备用电话>>")
                        if len(newPhone_e) == 11:
                            addrBook.modifyPerson(name, 'phone_e', newPhone_e)
                            print("------------电话2已经更新------------\n")
                            break
                        else:
                            print("---------输入有误，请重新输入！---------\n")
                            continue

                elif choice == "5":
                    while True:
                        newMail = input("请输入新的邮箱>>")
                        if "@" in mailInput:
                            addrBook.modifyPerson(name, 'mail', newMail)
                            print("------------邮箱已经更新------------\n")
                            break
                        else:
                            print("---------输入有误，请重新输入！---------\n")
                            continue

                elif choice == "6":
                    print("---退出修改功能---\n")
                    break

                else:
                    print("--修改的选项不存在，请重新输入！--")
                    continue


def modify_menu():
    print("------------请选择要修改的内容------------")
    print("--------------1：修改姓名----------------")
    print("--------------2：修改电话1---------------")
    print("--------------3：修改电话2---------------")
    print("--------------4：修改地址----------------")
    print("--------------5：修改邮箱----------------")
    print("--------------6：退出--------------------")


def main_menu():
    print("-----------请输入序号选择您要得功能----------")
    print("")
    print("-" * 14 + "1.录入联系人信息" + "-" * 14)
    print("-" * 43)
    print("-" * 14 + "2.浏览联系人信息" + "-" * 14)
    print("-" * 43)
    print("-" * 14 + "3.查询联系人信息" + "-" * 14)
    print("-" * 43)
    print("-" * 14 + "4.修改联系人信息" + "-" * 14)
    print("-" * 43)
    print("-" * 14 + "5.返回联系人信息" + "-" * 14)
    print("-" * 43)
    print("-" * 14 + "6.保存联系人信息" + "-" * 14)
    print("-" * 43)
    print("-" * 14 + "7.读取联系人信息" + "-" * 14)
    print("-" * 43)
    print("-" * 14 + "8.删除联系人信息" + "-" * 14)
    print("-" * 43)
    print("-" * 14 + "9.退出通讯录" + "-" * 18)
    print("")


def second_menu():
    print("---1:增加---2:浏览---3:查询---")
    print("---4:修改---5:返回---6:保存---")
    print("---7:读取---8:删除---9:退出---")

def start_system():
    main_menu()
    while True:
        choice = input("请输入相应数字操作>>")
        if choice == "1":
            pointer.add()
            second_menu()
            continue
        elif choice == "2":
            addrBook.browseAddrBook()
            second_menu()
            continue
        elif choice == "3":
            pointer.search()
            second_menu()
            continue
        elif choice == "4":
            pointer.modify()
            second_menu()
            continue
        elif choice == "5":
            main_menu()
            continue
        elif choice == "6":
            addrBook.save_to_file()
            second_menu()
            continue
        elif choice == "7":
            addrBook.recover_data()
            second_menu()
            continue
        elif choice == "8":
            pointer.delete()
            second_menu()
            continue
        elif choice == "9":
            print("---已经成功退出系统！---")
            break
        else:
            print("--------输入有误，请重新输入！--------")



if __name__ == '__main__':
    addrBook = AddressBook()
    pointer = Input()
    start_system()
